import express from 'express';
import requireAll from 'require-all';
import config from './config.js';
import nunjucks from 'nunjucks';
import path from 'path';
import bodyParser from 'body-parser';
import errorLog from './middleware/error-log.js';
import session from 'express-session';
import './mongoose.js';
const mongoStore = require('connect-mongo')(session);


// 获取动态路由
const routers = requireAll({
  dirname: path.join(__dirname, 'controller')
})

const app = express();
app.listen(config.port, () => {
  console.log(`${config.port}端口服务器已经开启`);
});
// 使用session
app.use(session({
  secret: 'liulang', // 加密字符串
  name: 'id',
  resave: false,
  saveUninitialized: true,
  cookie: {
    maxAge: 7 * 24 * 60 * 60
  },
  rolling: true,
  store: new mongoStore({
    url: config.mongodbPath,
    touchAfter: 24 * 3600
  })
}))
// 设置静态资源文件
app.use(express.static(config.publicPath));
// 设置模板文件
nunjucks.configure(config.viewsPath, {
  autoescape: true,
  express: app,
  noCache: true
});
// 解析post请求的数据，通过req.body获取
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
// 设置路由
for (let key in routers) {
  const e = routers[key];
  if (e && e.path && e.router) {
    app.use(e.path, e.router);
  }
}
// 500(记录错误日志)
app.use(errorLog);
// 设置404页面
app.use((req, res, next) => {
  res.status(404).render('./404.html');
});
